import pymysql

from utils.log_util import logger
from utils.read import base_data

data = base_data.read_ini()['mysql']
DB_CONF = {
    "host": data['MYSQL_HOST'],
    "port": int(data['MYSQL_PORT']),
    "user": data['MYSQL_USER'],
    "passwd": data['MYSQL_PASSWD'],
    "db": data['MYSQL_DB']
}


class MysqlDb:
    def __init__(self):
        # mysql链接
        self.conn = pymysql.connect(**DB_CONF, autocommit=True)
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 释放资源
    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def select_db_one(self, sql):
        logger.info(f"s执行sql: {sql}")
        self.cursor.execute(sql)
        # 获取数据
        # self.cursor.fetchall()
        return self.cursor.fetchone()

    def select_db_all(self, sql):
        logger.info(f"s执行sql: {sql}")
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def execute_db(self, sql):
        try:
            logger.info(f'执行sql：{sql}')
            self.cursor.execute(sql)
            self.cursor.commit()
        except Exception as e:
            logger.info("执行SQL出错了".format(e))

    # def execute_many(self, sql, params=None):
    #     self.cursor.executemany(sql, params)
    #     return self.cursor.fetchall()
    #
    # def execute_last_id(self, sql, params=None):
    #     self.cursor.execute(sql, params)


db = MysqlDb()
if __name__ == "__main__":
    db = MysqlDb()
    # result = db.select_db_one("select code from users_verifycode where mobile = 17683911321 order by id desc")
    # print(result['code'])
    # results = db.select_db_all("select * from users_userprofile order by id desc limit 10")
    # results = db.select_db_all("select count(id)as banner_num from goods_banner")
    results = db.select_db_one("select    id    from users_userprofile where    mobile = '17683911366'")
    results = db.select_db_one("select nums from trade_shoppingcart where user_id='228350' and goods_id = 3" )
    print(results)

    # db.execute_db("delete from users_userprofile where mobile = '17683911321'")
